package com.warthur.spring.shiro.controller;

import com.warthur.spring.shiro.common.util.JwtUtils;
import com.warthur.spring.shiro.pojo.JwtToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @author warthur
 * @date 2018/09/08
 */
@RestController
@Slf4j
public class HomeController {

    @GetMapping("/home")
    @RequiresPermissions("deviceManage")
    public String home() {
        return "hello world";
    }

    @GetMapping("/index")
    public String unAuthorized() {
        return "index";
    }

    @GetMapping("/login")
    public String login(String username, String password) {
        try {
            // 验证用户名密码是否合法
            return JwtUtils.token(username);
        } catch (Exception e) {
            log.error("登录失败，用户名[{}]", username, e);
        }
        return "error";
    }

    /**
     * 使用权限管理工具进行用户的退出
     *
     * @return string
     */
    @GetMapping("/logout")
    public String logout() {

        //使用权限管理工具进行用户的退出
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        return "退出成功";
    }
}
